// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
//商户配置
const mch_id = '1642611741' //商户号
//数据库服务
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID

  let functionName = 'pay_callback' //结果通知回调云函数名:接收微信支付异步通知回调的云函数名
  let subMchId = mch_id //微信支付分配的子商户号
  //let deviceInfo =   //终端设备号(门店号或收银设备ID)，注意：PC网页或公众号内支付请传"WEB"
  let nonceStr = Math.random().toString(36).substr(2, 13) //随机字符串，不长于32位。推荐随机数生成算法
  let timeStamp = parseInt(Date.now() / 1000)
  let outTradeNo = 'CHFS' + timeStamp + nonceStr //商户系统内部订单号，要求32个字符内，只能是数字、大小写字母_-
  //let feeType = 'CNY' //符合ISO 4217标准的三位字母代码，默认人民币：CNY
  let tradeType = 'JSAPI'
  let {
    body,  //商品简单描述
    detail, //商品详情
    attach,  //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
    totalFee //订单总金额，只能为整数(单位：分)
  } = event
  //订单商品信息不能空，避免空商品订单的情况
  if (!detail || detail.trim().length == 0) {
    return {
      errCode: -1,
      errMsg: 'detail入参不能为空'
    }
  }

  var goodsFeeSum = 0 //商品金额累加器
  try {
    var arry = JSON.parse(detail.replace(/"_id"/g, '"parameter_id"'));
    var length = arry.length;
    for (var i = 0; i < length; i++) {
      //获取商品信息，避免抓包修改支付信息
      let goodInfo = (await db.collection('good').doc(arry[i].g_id).get()).data
      let studentInfo = (await db.collection('student').doc(arry[i].s_id).get()).data
      delete goodInfo._id
      delete studentInfo._id
      const nowTime = Date.now()
      //处理金额字符串
      var money
      if ((typeof goodInfo.price) == "number") {
        money = goodInfo.price * 100
      }
      if ((typeof goodInfo.price) == "string") {
        if (goodInfo.price.indexOf('.') != -1) {
          let moneyArray = goodInfo.price.split('.')
          money = parseInt(moneyArray[0]) * 100 + parseInt(moneyArray[1].substring(0, 2))
        } else {
          money = parseInt(goodInfo.price) * 100
        }
      }

      //累加订单金额
      goodsFeeSum = goodsFeeSum + money * arry[i].number
      //写入商品订单
      db.collection("goods_order").add({
        data: {
          //插入商品信息
          g_description: goodInfo.description,
          g_img: goodInfo.img,
          g_name: goodInfo.name,
          g_price: goodInfo.price,
          g_tag: goodInfo.tag,
          g_title: goodInfo.title,
          //插入学生信息
          s_i_id: studentInfo.i_id,
          s_grade: studentInfo.grade,
          s_class: studentInfo.class,
          s_name: studentInfo.name,
          s_sex: studentInfo.sex,
          s_u_id: studentInfo.u_id,
          //支付订单号，商户内部订单号
          outTradeNo: outTradeNo,
          //数量
          number: arry[i].number,
          //尺码信息
          parameter: arry[i].parameter,
          //原始信息
          initialInfo: arry[i],
          //status: 'INIT',
          status: outTradeNo,
          createTime: nowTime,
          modifyTime: nowTime
        }
      })
    }
  } catch (e) {
    return {
      errCode: -1,
      errMsg: '处理订单商品信息异常,请检查或重试',
      detail,
      exceptional: e
    }
  }

  //db写入：预支付交易单信息
  const nowTime = Date.now()
  const userInfo = (await db.collection("user").where({
    openid: openid
  }).get()).data[0]
  db.collection("order").add({
    data: {
      _id: outTradeNo,
      _openid: openid,
      userphone: userInfo.phone,
      username: userInfo.username,
      body,
      detail,
      attach,
      nonceStr,
      tradeType,
      outTradeNo,
      totalFee: goodsFeeSum,//直接使用根据商品信息计算的金额进行下单，不再校验及使用云函数入参totalFee
      status: 'INIT',
      createTime: nowTime,
      modifyTime: nowTime
    }
  })
  //生成预支付交易单
  const result = await cloud.cloudPay.unifiedOrder({
    body,
    detail,
    attach,
    nonceStr,
    tradeType,
    outTradeNo,
    spbillCreateIp: '127.0.0.1', //调用微信支付API的机器IP
    subMchId,
    totalFee: goodsFeeSum,
    envId: 'ops-0gnuzw0q7bcf4c1a-2b7045716cf', //接收微信支付异步通知回调的云函数所在的环境ID
    functionName
  })

  if (result.returnCode != "SUCCESS") {
    return {
      errCode: result.returnCode,
      errMsg: result.returnMsg
    }
  }
  if (result.resultCode != "SUCCESS") {
    return {
      errCode: result.resultCode,
      errMsg: result.errCodeDes
    }
  }
  //不再校验，直接使用根据商品计算金额下单
  // //校验商品金额
  // if (goodsFeeSum != totalFee) {
  //   //关闭订单
  //   cloud.callFunction({
  //     name: 'server_Order',
  //     data: {
  //       type: 'closeOrder',
  //       outTradeNo,
  //     }
  //   }).then(
  //     db.collection('order')
  //       .where({
  //         outTradeNo: outTradeNo
  //       })
  //       .update({
  //         data: {
  //           checkSign: '订单违法被关闭'
  //         },
  //       })
  //   )
  //   return {
  //     errCode: -1,
  //     errMsg: '订单违法被关闭:商品总金额:' + goodsFeeSum + ' 和订单金额:' + totalFee + ' 不一致'
  //   }
  // }
  //更新订单为待支付状态
  await db.collection('order')
    .where({
      outTradeNo: outTradeNo
    })
    .update({
      data: {
        status: 'NOTPAY',
        payment: result.payment,
        modifyTime: Date.now()
      },
    });
  // db.collection('goods_order')
  //   .where({
  //     outTradeNo: outTradeNo
  //   })
  //   .update({
  //     data: {
  //       status: 'NOTPAY',
  //       modifyTime: Date.now()
  //     },
  //   });

  return result
}